package com.kkd.kkdapp.patternlock;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Debug;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityManager;

import com.kkd.kkdapp.R;

@SuppressLint("ClickableViewAccessibility")
public class PatternView extends View {

	private static final boolean PROFILE_DRAWING = false;
	private boolean mDrawingProfilingStarted = false;

	private Paint mPaint = new Paint();
	private Paint mPathPaint = new Paint();
	/**
	 * How many milliseconds we spend animating each circle of a pattern if the
	 * animating mode is set. The entire animation should take this constant *
	 * the length of the pattern to complete.
	 */
	private static final int MILLIS_PER_CIRCLE_ANIMATING = 700;

	/**
	 * This can be used to avoid updating the display for very small motions or
	 * noisy panels. It didn't seem to have much impact on the devices tested,
	 * so currently set to 0.
	 */
	private static final float DRAG_THRESHOLD = 0.0f;

	private OnPatternListener mOnPatternListener;
	private ArrayList<Cell> mPattern = new ArrayList<Cell>(9);

	/**
	 * Lookup table for the circles of the pattern we are currently drawing.
	 * This will be the cells of the complete pattern unless we are animating,
	 * in which case we use this to hold the cells we are drawing for the in
	 * progress animation.
	 */
	private boolean[][] mPatternDrawLookup = new boolean[3][3];

	/**
	 * the in progress point: - during interaction: where the user's finger is -
	 * during animation: the current tip of the animating line
	 */
	private float mInProgressX = -1;
	private float mInProgressY = -1;

	private long mAnimatingPeriodStart;

	private DisplayMode mDisplayMode = DisplayMode.Correct;
	private boolean mInputEnabled = true;
	private boolean mInStealthMode = false;
	private boolean mPatternInProgress = false;

	private float mDiameterFactor = 0.10f; // TODO: move to attrs
	private final int mStrokeAlpha = 128;
	private float mHitFactor = 0.6f;

	private float mSquareWidth;
	private float mSquareHeight;

	private Bitmap mBitmapDotDefault;
	private Bitmap mBitmapDotTouched;
	private Bitmap mBitmapCircleDefault;
	private Bitmap mBitmapCircle;
	private Path mCurrentPath = new Path();
	private Rect mInvalidate = new Rect();
	private Rect mTmpInvalidateRect = new Rect();

	private int mBitmapWidth; // 各bitmap中最大值
	private int mBitmapHeight; // 各bitmap中最大值

	/**
	 * Represents a cell in the 3 X 3 matrix of the pattern view.
	 */
	public static class Cell {
		int row;
		int column;

		// keep # objects limited to 9
		static Cell[][] sCells = new Cell[3][3];
		static {
			for (int i = 0; i < 3; i++) {
				for (int j = 0; j < 3; j++) {
					sCells[i][j] = new Cell(i, j);
				}
			}
		}

		/**
		 * @param row
		 *            The row of the cell.
		 * @param column
		 *            The column of the cell.
		 */
		private Cell(int row, int column) {
			checkRange(row, column);
			this.row = row;
			this.column = column;
		}

		public int getRow() {
			return row;
		}

		public int getColumn() {
			return column;
		}

		/**
		 * @param row
		 *            The row of the cell.
		 * @param column
		 *            The column of the cell.
		 */
		public static synchronized Cell of(int row, int column) {
			checkRange(row, column);
			return sCells[row][column];
		}

		private static void checkRange(int row, int column) {
			if (row < 0 || row > 2) {
				throw new IllegalArgumentException("row must be in range 0-2");
			}
			if (column < 0 || column > 2) {
				throw new IllegalArgumentException(
						"column must be in range 0-2");
			}
		}

		public String toString() {
			return "(row=" + row + ",clmn=" + column + ")";
		}
	}

	/**
	 * How to display the current pattern.
	 */
	public enum DisplayMode {

		Correct, // The pattern drawn is correct (i.e draw it in a friendly
					// color)
		Animate, // Animate the pattern (for demo, and help).
		Wrong// The pattern is wrong (i.e draw a foreboding color)
	}

	/**
	 * The call back interface for detecting patterns entered by the user.
	 */
	public interface OnPatternListener {

		/**
		 * A new pattern has begun.
		 */
		void onPatternStart();

		/**
		 * The pattern was cleared.
		 */
		void onPatternCleared();

		/**
		 * The user extended the pattern currently being drawn by one cell.
		 * 
		 * @param pattern
		 *            The pattern with newly added cell.
		 */
		void onPatternCellAdded(List<Cell> pattern);

		/**
		 * A pattern was detected from the user.
		 * 
		 * @param pattern
		 *            The pattern.
		 */
		void onPatternDetected(List<Cell> pattern);
	}

	public PatternView(Context context) {
		super(context);
		initUI();
	}

	public PatternView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initUI();
	}

	public PatternView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initUI();

	}

	/**
	 * @author askzhao
	 */
	private void initUI() {

		setClickable(true);

		mPathPaint.setAntiAlias(true);
		mPathPaint.setDither(true);
		int pathColor = getResources().getColor(R.color.orange_ffbc5c);
		mPathPaint.setColor(pathColor);
		mPathPaint.setAlpha(mStrokeAlpha);
		mPathPaint.setStyle(Paint.Style.STROKE);
		mPathPaint.setStrokeJoin(Paint.Join.ROUND);
		mPathPaint.setStrokeCap(Paint.Cap.ROUND);

		// lots of bitmaps!
		mBitmapDotDefault = BitmapFactory.decodeResource(getResources(),
				R.drawable.pl_patternview_dot_default);
		mBitmapDotTouched = BitmapFactory.decodeResource(getResources(),
				R.drawable.pl_patternview_dot_touched);
		mBitmapCircleDefault = BitmapFactory.decodeResource(getResources(),
				R.drawable.pl_patternview_circle_default_alpha);
		mBitmapCircle = BitmapFactory.decodeResource(getResources(),
				R.drawable.pl_patternview_circle_alpha);
		// bitmaps have the size of the largest bitmap in this group
		final Bitmap bitmaps[] = { mBitmapDotDefault, mBitmapDotTouched,
				mBitmapCircleDefault, mBitmapCircle };
		for (Bitmap bitmap : bitmaps) {
			mBitmapWidth = Math.max(mBitmapWidth, bitmap.getWidth());
			mBitmapHeight = Math.max(mBitmapHeight, bitmap.getHeight());
		}

		mPaint.setAntiAlias(true);
		mPaint.setDither(true);
		mPaint.setFilterBitmap(true);
	}

	/**
	 * @return Whether the view is in stealth mode.
	 */
	public boolean isInStealthMode() {
		return mInStealthMode;
	}

	/**
	 * Set whether the view is in stealth mode. If true, there will be no
	 * visible feedback as the user enters the pattern.
	 * 
	 * @param inStealthMode
	 *            Whether in stealth mode.
	 */
	public void setInStealthMode(boolean inStealthMode) {
		mInStealthMode = inStealthMode;
	}

	public boolean behavesInStealthMode() {
		return mInStealthMode && mDisplayMode == DisplayMode.Correct;
	}

	/**
	 * Set the call back for pattern detection.
	 * 
	 * @param onPatternListener
	 *            The call back.
	 */
	public void setOnPatternListener(OnPatternListener onPatternListener) {
		mOnPatternListener = onPatternListener;
	}

	/**
	 * Set the pattern explicitely (rather than waiting for the user to input a
	 * pattern).
	 * 
	 * @param displayMode
	 *            How to display the pattern.
	 * @param pattern
	 *            The pattern.
	 */
	public void setPattern(DisplayMode displayMode, List<Cell> pattern) {
		mPattern.clear();
		mPattern.addAll(pattern);
		clearPatternDrawLookup();
		for (Cell cell : pattern) {
			mPatternDrawLookup[cell.getRow()][cell.getColumn()] = true;
		}

		setDisplayMode(displayMode);
	}

	public DisplayMode getDisplayMode() {
		return mDisplayMode;
	}

	/**
	 * Set the display mode of the current pattern. This can be useful, for
	 * instance, after detecting a pattern to tell this view whether change the
	 * in progress result to correct or wrong.
	 * 
	 * @param displayMode
	 *            The display mode.
	 */
	public void setDisplayMode(DisplayMode displayMode) {
		mDisplayMode = displayMode;
		if (displayMode == DisplayMode.Animate) {
			if (mPattern.size() == 0) {
				throw new IllegalStateException(
						"you must have a pattern to "
								+ "animate if you want to set the display mode to animate");
			}
			mAnimatingPeriodStart = SystemClock.elapsedRealtime();
			final Cell first = mPattern.get(0);
			mInProgressX = getCenterXForColumn(first.getColumn());
			mInProgressY = getCenterYForRow(first.getRow());
			clearPatternDrawLookup();
		}
		invalidate();
	}

	private void notifyCellAdded() {
		if (mOnPatternListener != null) {
			mOnPatternListener.onPatternCellAdded(mPattern);
		}
	}

	private void notifyPatternStarted() {
		if (mOnPatternListener != null) {
			mOnPatternListener.onPatternStart();
		}
	}

	private void notifyPatternDetected() {
		if (mOnPatternListener != null) {
			mOnPatternListener.onPatternDetected(mPattern);
		}
	}

	private void notifyPatternCleared() {
		if (mOnPatternListener != null) {
			mOnPatternListener.onPatternCleared();
		}
	}

	/**
	 * Clear the pattern.
	 */
	public void clearPattern() {
		resetPattern();
	}

	/**
	 * Reset all pattern state.
	 */
	private void resetPattern() {
		mPattern.clear();
		clearPatternDrawLookup();
		mDisplayMode = DisplayMode.Correct;
		invalidate();
	}

	/**
	 * Clear the pattern lookup table.
	 */
	private void clearPatternDrawLookup() {
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 3; j++) {
				mPatternDrawLookup[i][j] = false;
			}
		}
	}

	public boolean isInputEnabled() {
		return mInputEnabled;
	}

	/**
	 * Enable or disable input. (for instance when displaying a message that
	 * will timeout so user doesn't get view into messy state).
	 */
	public void setInputEnabled(boolean inputEnabled) {
		mInputEnabled = inputEnabled;
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		final int width = w - getPaddingLeft() - getPaddingRight();
		mSquareWidth = width / 3.0f;

		final int height = h - getPaddingTop() - getPaddingBottom();
		mSquareHeight = height / 3.0f;
	}

	private int resolveMeasured(int measureSpec, int desired) {
		int result = 0;
		int specSize = MeasureSpec.getSize(measureSpec);
		switch (MeasureSpec.getMode(measureSpec)) {
		case MeasureSpec.UNSPECIFIED:
			result = desired;
			break;
		case MeasureSpec.AT_MOST:
			result = Math.max(specSize, desired);
			break;
		case MeasureSpec.EXACTLY:
		default:
			result = specSize;
		}
		return result;
	}

	@Override
	protected int getSuggestedMinimumWidth() {
		// View should be large enough to contain 3 side-by-side target bitmaps
		return 3 * mBitmapWidth;
	}

	@Override
	protected int getSuggestedMinimumHeight() {
		// View should be large enough to contain 3 side-by-side target bitmaps
		return 3 * mBitmapWidth;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		final int minimumWidth = getSuggestedMinimumWidth();
		final int minimumHeight = getSuggestedMinimumHeight();
		int viewWidth = resolveMeasured(widthMeasureSpec, minimumWidth);
		int viewHeight = resolveMeasured(heightMeasureSpec, minimumHeight);

		viewWidth = viewHeight = Math.min(viewWidth, viewHeight);
		setMeasuredDimension(viewWidth, viewHeight);
	}

	/*
	 * 重写保证控件为正方形
	 */
	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		int min = Math.min(right - left, bottom - top);
		super.onLayout(changed, left, top, left + min, top + min);
	}

	/**
	 * Determines whether the point x, y will add a new point to the current
	 * pattern (in addition to finding the cell, also makes heuristic choices
	 * such as filling in gaps based on current pattern).
	 * 
	 * @param x
	 *            The x coordinate.
	 * @param y
	 *            The y coordinate.
	 */
	private Cell detectAndAddHit(float x, float y) {
		final Cell cell = checkForNewHit(x, y);
		if (cell != null) {

			// check for gaps in existing pattern
			Cell fillInGapCell = null;
			final ArrayList<Cell> pattern = mPattern;
			if (!pattern.isEmpty()) {
				final Cell lastCell = pattern.get(pattern.size() - 1);
				int dRow = cell.row - lastCell.row;
				int dColumn = cell.column - lastCell.column;

				int fillInRow = lastCell.row;
				int fillInColumn = lastCell.column;

				if (Math.abs(dRow) == 2 && Math.abs(dColumn) != 1) {
					fillInRow = lastCell.row + ((dRow > 0) ? 1 : -1);
				}

				if (Math.abs(dColumn) == 2 && Math.abs(dRow) != 1) {
					fillInColumn = lastCell.column + ((dColumn > 0) ? 1 : -1);
				}

				fillInGapCell = Cell.of(fillInRow, fillInColumn);
			}

			if (fillInGapCell != null
					&& !mPatternDrawLookup[fillInGapCell.row][fillInGapCell.column]) {
				addCellToPattern(fillInGapCell);
			}
			addCellToPattern(cell);
			performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
			return cell;
		}
		return null;
	}

	private void addCellToPattern(Cell newCell) {
		mPatternDrawLookup[newCell.getRow()][newCell.getColumn()] = true;
		mPattern.add(newCell);
		notifyCellAdded();
	}

	// helper method to find which cell a point maps to
	private Cell checkForNewHit(float x, float y) {

		final int rowHit = getRowHit(y);
		if (rowHit < 0) {
			return null;
		}
		final int columnHit = getColumnHit(x);
		if (columnHit < 0) {
			return null;
		}

		if (mPatternDrawLookup[rowHit][columnHit]) {
			return null;
		}
		return Cell.of(rowHit, columnHit);
	}

	/**
	 * Helper method to find the row that y falls into.
	 * 
	 * @param y
	 *            The y coordinate
	 * @return The row that y falls in, or -1 if it falls in no row.
	 */
	private int getRowHit(float y) {

		final float squareHeight = mSquareHeight;
		float hitSize = squareHeight * mHitFactor;

		float offset = getPaddingTop() + (squareHeight - hitSize) / 2f;
		for (int i = 0; i < 3; i++) {

			final float hitTop = offset + squareHeight * i;
			if (y >= hitTop && y <= hitTop + hitSize) {
				return i;
			}
		}
		return -1;
	}

	/**
	 * Helper method to find the column x fallis into.
	 * 
	 * @param x
	 *            The x coordinate.
	 * @return The column that x falls in, or -1 if it falls in no column.
	 */
	private int getColumnHit(float x) {
		final float squareWidth = mSquareWidth;
		float hitSize = squareWidth * mHitFactor;

		float offset = getPaddingLeft() + (squareWidth - hitSize) / 2f;
		for (int i = 0; i < 3; i++) {

			final float hitLeft = offset + squareWidth * i;
			if (x >= hitLeft && x <= hitLeft + hitSize) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public boolean onHoverEvent(MotionEvent event) {
		if (((AccessibilityManager) getContext().getSystemService(
				Context.ACCESSIBILITY_SERVICE)).isTouchExplorationEnabled()) {
			final int action = event.getAction();
			switch (action) {
			case MotionEvent.ACTION_HOVER_ENTER:
				event.setAction(MotionEvent.ACTION_DOWN);
				break;
			case MotionEvent.ACTION_HOVER_MOVE:
				event.setAction(MotionEvent.ACTION_MOVE);
				break;
			case MotionEvent.ACTION_HOVER_EXIT:
				event.setAction(MotionEvent.ACTION_UP);
				break;
			}
			onTouchEvent(event);
			event.setAction(action);
		}
		return super.onHoverEvent(event);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (!mInputEnabled || !isEnabled()) {
			return false;
		}

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			handleActionDown(event);
			return true;
		case MotionEvent.ACTION_UP:
			handleActionUp(event);
			return true;
		case MotionEvent.ACTION_MOVE:
			handleActionMove(event);
			return true;
		case MotionEvent.ACTION_CANCEL:
			if (mPatternInProgress) {
				mPatternInProgress = false;
				resetPattern();
				notifyPatternCleared();
			}
			if (PROFILE_DRAWING) {
				if (mDrawingProfilingStarted) {
					Debug.stopMethodTracing();
					mDrawingProfilingStarted = false;
				}
			}
			return true;
		}
		return false;
	}

	private void handleActionMove(MotionEvent event) {
		// Handle all recent motion events so we don't skip any cells even when
		// the device
		// is busy...
		final float radius = (mSquareWidth * mDiameterFactor * 0.5f);
		final int historySize = event.getHistorySize();
		mTmpInvalidateRect.setEmpty();
		boolean invalidateNow = false;
		for (int i = 0; i < historySize + 1; i++) {
			final float x = i < historySize ? event.getHistoricalX(i) : event
					.getX();
			final float y = i < historySize ? event.getHistoricalY(i) : event
					.getY();
			Cell hitCell = detectAndAddHit(x, y);
			final int patternSize = mPattern.size();
			if (hitCell != null && patternSize == 1) {
				mPatternInProgress = true;
				notifyPatternStarted();
			}
			// note current x and y for rubber banding of in progress patterns
			final float dx = Math.abs(x - mInProgressX);
			final float dy = Math.abs(y - mInProgressY);
			if (dx > DRAG_THRESHOLD || dy > DRAG_THRESHOLD) {
				invalidateNow = true;
			}

			if (mPatternInProgress && patternSize > 0) {
				final ArrayList<Cell> pattern = mPattern;
				final Cell lastCell = pattern.get(patternSize - 1);
				float lastCellCenterX = getCenterXForColumn(lastCell.column);
				float lastCellCenterY = getCenterYForRow(lastCell.row);

				// Adjust for drawn segment from last cell to (x,y). Radius
				// accounts for line width.
				float left = Math.min(lastCellCenterX, x) - radius;
				float right = Math.max(lastCellCenterX, x) + radius;
				float top = Math.min(lastCellCenterY, y) - radius;
				float bottom = Math.max(lastCellCenterY, y) + radius;

				// Invalidate between the pattern's new cell and the pattern's
				// previous cell
				if (hitCell != null) {
					final float width = mSquareWidth * 0.5f;
					final float height = mSquareHeight * 0.5f;
					final float hitCellCenterX = getCenterXForColumn(hitCell.column);
					final float hitCellCenterY = getCenterYForRow(hitCell.row);

					left = Math.min(hitCellCenterX - width, left);
					right = Math.max(hitCellCenterX + width, right);
					top = Math.min(hitCellCenterY - height, top);
					bottom = Math.max(hitCellCenterY + height, bottom);
				}

				// Invalidate between the pattern's last cell and the previous
				// location
				mTmpInvalidateRect.union(Math.round(left), Math.round(top),
						Math.round(right), Math.round(bottom));
			}
		}
		mInProgressX = event.getX();
		mInProgressY = event.getY();

		// To save updates, we only invalidate if the user moved beyond a
		// certain amount.
		if (invalidateNow) {
			mInvalidate.union(mTmpInvalidateRect);
			invalidate(mInvalidate);
			mInvalidate.set(mTmpInvalidateRect);
		}
	}

	private void handleActionUp(MotionEvent event) {
		// report pattern detected
		if (!mPattern.isEmpty()) {
			mPatternInProgress = false;
			notifyPatternDetected();
			invalidate();
		}
		if (PROFILE_DRAWING) {
			if (mDrawingProfilingStarted) {
				Debug.stopMethodTracing();
				mDrawingProfilingStarted = false;
			}
		}
	}

	private void handleActionDown(MotionEvent event) {
		resetPattern();
		final float x = event.getX();
		final float y = event.getY();
		final Cell hitCell = detectAndAddHit(x, y);
		if (hitCell != null) {
			mPatternInProgress = true;
			mDisplayMode = DisplayMode.Correct;
			notifyPatternStarted();
		} else if (mPatternInProgress) {
			mPatternInProgress = false;
			notifyPatternCleared();
		}
		if (hitCell != null) {
			final float startX = getCenterXForColumn(hitCell.column);
			final float startY = getCenterYForRow(hitCell.row);

			final float widthOffset = mSquareWidth / 2f;
			final float heightOffset = mSquareHeight / 2f;

			invalidate((int) (startX - widthOffset),
					(int) (startY - heightOffset),
					(int) (startX + widthOffset), (int) (startY + heightOffset));
		}
		mInProgressX = x;
		mInProgressY = y;
		if (PROFILE_DRAWING) {
			if (!mDrawingProfilingStarted) {
				Debug.startMethodTracing("PatternDrawing");
				mDrawingProfilingStarted = true;
			}
		}
	}

	private float getCenterXForColumn(int column) {
		float ret = 0;
		int padding = getPaddingLeft();
		ret = padding + column * mSquareWidth + mSquareWidth / 2f;
		return ret;
	}

	private float getCenterYForRow(int row) {
		return getPaddingTop() + row * mSquareHeight + mSquareHeight / 2f;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		final ArrayList<Cell> pattern = mPattern;
		final int count = pattern.size();
		final boolean[][] drawLookup = mPatternDrawLookup;

		if (mDisplayMode == DisplayMode.Animate) {

			// figure out which circles to draw

			// + 1 so we pause on complete pattern
			final int oneCycle = (count + 1) * MILLIS_PER_CIRCLE_ANIMATING;
			final int spotInCycle = (int) (SystemClock.elapsedRealtime() - mAnimatingPeriodStart)
					% oneCycle;
			final int numCircles = spotInCycle / MILLIS_PER_CIRCLE_ANIMATING;

			clearPatternDrawLookup();
			for (int i = 0; i < numCircles; i++) {
				final Cell cell = pattern.get(i);
				drawLookup[cell.getRow()][cell.getColumn()] = true;
			}

			// figure out in progress portion of ghosting line

			final boolean needToUpdateInProgressPoint = numCircles > 0
					&& numCircles < count;

			if (needToUpdateInProgressPoint) {
				final float percentageOfNextCircle = ((float) (spotInCycle % MILLIS_PER_CIRCLE_ANIMATING))
						/ MILLIS_PER_CIRCLE_ANIMATING;

				final Cell currentCell = pattern.get(numCircles - 1);
				final float centerX = getCenterXForColumn(currentCell.column);
				final float centerY = getCenterYForRow(currentCell.row);

				final Cell nextCell = pattern.get(numCircles);
				final float dx = percentageOfNextCircle
						* (getCenterXForColumn(nextCell.column) - centerX);
				final float dy = percentageOfNextCircle
						* (getCenterYForRow(nextCell.row) - centerY);
				mInProgressX = centerX + dx;
				mInProgressY = centerY + dy;
			}
			// TODO: Infinite loop here...
			invalidate();
		}

		final float squareWidth = mSquareWidth;

		float radius = (squareWidth * mDiameterFactor * 0.3f);
		mPathPaint.setStrokeWidth(radius);

		final Path currentPath = mCurrentPath;
		currentPath.rewind();

		// Reset the alpha to draw normally
		mPaint.setAlpha(255);

		// TODO: the path should be created and cached every time we hit-detect
		// a cell
		// only the last segment of the path should be computed here
		// draw the path of the pattern (unless we are in stealth mode)

		if (!behavesInStealthMode()) {
			boolean anyCircles = false;
			for (int i = 0; i < count; i++) {
				Cell cell = pattern.get(i);

				// only draw the part of the pattern stored in
				// the lookup table (this is only different in the case
				// of animation).
				if (!drawLookup[cell.row][cell.column]) {
					break;
				}
				anyCircles = true;

				float centerX = getCenterXForColumn(cell.column);
				float centerY = getCenterYForRow(cell.row);

				if (i == 0) {
					currentPath.moveTo(centerX, centerY);
				} else {
					currentPath.lineTo(centerX, centerY);
				}
			}

			// add last in progress section
			if ((mPatternInProgress || mDisplayMode == DisplayMode.Animate)
					&& anyCircles) {
				currentPath.lineTo(mInProgressX, mInProgressY);
			}
			canvas.drawPath(currentPath, mPathPaint);
		}
		// draw the circles

		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 3; j++) {
				float centerX = getCenterXForColumn(j);
				float centerY = getCenterYForRow(i);
				drawCircle(canvas, (int) centerX, (int) centerY,
						drawLookup[i][j]);
			}
		}

		// draw small pattern grid
		if (mOnPatternDrawListener != null)
			mOnPatternDrawListener.onPatternDraw(drawLookup);
	}

	/**
	 * @param canvas
	 * @param leftX
	 * @param topY
	 * @param partOfPattern
	 *            Whether this circle is part of the pattern.
	 */
	private void drawCircle(Canvas canvas, float cX, float cY,
			boolean partOfPattern) {
		Bitmap outerCircle;
		if (!partOfPattern || behavesInStealthMode()) {
			outerCircle = mBitmapCircleDefault;
		} else if (mPatternInProgress) {
			outerCircle = mBitmapCircle;
		} else if (mDisplayMode == DisplayMode.Wrong) {
			outerCircle = mBitmapDotTouched;
		} else if (mDisplayMode == DisplayMode.Correct
				|| mDisplayMode == DisplayMode.Animate) {
			outerCircle = mBitmapCircle;
		} else {
			throw new IllegalStateException("unknown display mode "
					+ mDisplayMode);
		}
		int width = outerCircle.getWidth();
		int height = outerCircle.getHeight();
		canvas.drawBitmap(outerCircle, cX - width / 2, cY - height / 2, mPaint);
	}

	@SuppressWarnings("deprecation")
	@Override
	protected Parcelable onSaveInstanceState() {
		Parcelable superState = super.onSaveInstanceState();
		return new SavedState(superState,
				PatternUtils.patternToString(mPattern), mDisplayMode.ordinal(),
				mInputEnabled, mInStealthMode);
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onRestoreInstanceState(Parcelable state) {
		try {
			final SavedState ss = (SavedState) state;
			super.onRestoreInstanceState(ss.getSuperState());
			setPattern(DisplayMode.Correct,
					PatternUtils.stringToPattern(ss.getSerializedPattern()));
			mDisplayMode = DisplayMode.values()[ss.getDisplayMode()];
			mInputEnabled = ss.isInputEnabled();
			mInStealthMode = ss.isInStealthMode();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private OnPatternDrawListener mOnPatternDrawListener;

	public void setOnPatternDrawListener(OnPatternDrawListener listener) {
		mOnPatternDrawListener = listener;
	}

	public interface OnPatternDrawListener {
		public void onPatternDraw(boolean[][] drawLookup);
	}

	/**
	 * The parecelable for saving and restoring a pattern view.
	 */
	private static class SavedState extends BaseSavedState {

		private final String mSerializedPattern;
		private final int mDisplayMode;
		private final boolean mInputEnabled;
		private final boolean mInStealthMode;

		/**
		 * Constructor called from {@link PatternView#onSaveInstanceState()}
		 */
		private SavedState(Parcelable superState, String serializedPattern,
				int displayMode, boolean inputEnabled, boolean inStealthMode) {
			super(superState);
			mSerializedPattern = serializedPattern;
			mDisplayMode = displayMode;
			mInputEnabled = inputEnabled;
			mInStealthMode = inStealthMode;
		}

		/**
		 * Constructor called from {@link #CREATOR}
		 */
		private SavedState(Parcel in) {
			super(in);
			mSerializedPattern = in.readString();
			mDisplayMode = in.readInt();
			mInputEnabled = (Boolean) in.readValue(null);
			mInStealthMode = (Boolean) in.readValue(null);
		}

		public String getSerializedPattern() {
			return mSerializedPattern;
		}

		public int getDisplayMode() {
			return mDisplayMode;
		}

		public boolean isInputEnabled() {
			return mInputEnabled;
		}

		public boolean isInStealthMode() {
			return mInStealthMode;
		}

		@Override
		public void writeToParcel(Parcel dest, int flags) {
			super.writeToParcel(dest, flags);
			dest.writeString(mSerializedPattern);
			dest.writeInt(mDisplayMode);
			dest.writeValue(mInputEnabled);
			dest.writeValue(mInStealthMode);
		}

	}
}
